package com.xiachufang.app.service;

import com.xiachufang.app.dao.CategoryDao;
import com.xiachufang.app.entity.Category;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class CategoryService {

    @Resource
    private CategoryDao categoryDao;

    public List<Category> list() {
        return categoryDao.findAll();
    }

    /**
     * 查询父子菜谱分类
     * @return 父子分类集合
     */
    public List<Category> findChildren() {
        List<Category> all = categoryDao.findAll();
        // java8 stream语法 筛选 pid为null的一级分类
        List<Category> parentList = all.stream().filter(category -> category.getPid() == null).collect(Collectors.toList());
        for (Category parent : parentList) {
            // 找到当前分类的全部子分类
            List<Category> children = all.stream().filter(c -> parent.getId().equals(c.getPid())).collect(Collectors.toList());
            parent.setChildren(children);
        }
        return parentList;
    }

    public void save(Category category) {
        categoryDao.save(category);
    }

    public void delete(Integer id) {
        try {
            categoryDao.deleteById(id);
        } catch (EmptyResultDataAccessException e) {
            System.err.println("删除失败， 未找到数据");
        }
    }

    public List<Category> home() {
        return categoryDao.getHome();
    }

    public Page<Category> findPage(Pageable pageRequest, String name) {
        return categoryDao.findPage(pageRequest, name);
    }
}
